package com.abel.bigwater.data

import com.abel.bigwater.msg.RtuMsg
import com.alibaba.fastjson.JSON
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Component

@Component
class MsgHelper {
    @Autowired
    var msgTemp: KafkaTemplate<String, Any>? = null

    @Value("\${topic.raw.jnrq}")
    var rawTopic: String? = null

    @Value("\${topic.handle.jnrq}")
    var handleTopic: String? = null

    fun sendRawPacket(rmsg: RtuMsg) {
        val json = JSON.toJSONString(rmsg)
        val r1 = msgTemp!!.send(rawTopic!!, rmsg.station.orEmpty(), json)

        if (1.rangeTo(10).random() == 5) {
            lgr.info("send to kafka {} done?{}/cancel?{} : {}/{}...",
                    rawTopic, r1.isDone, r1.isCancelled, rmsg.station, json.take(100))
        }
    }

    fun sendHandleTopic(rmsg: RtuMsg) {
        val json = JSON.toJSONString(rmsg)
        val r1 = msgTemp!!.send(handleTopic!!, rmsg.station.orEmpty(), json)

        lgr.info("send to kafka {} done?{}/cancel?{} : {}/{}...",
                rawTopic, r1.isDone, r1.isCancelled, rmsg.station, json.take(100))
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(MsgHelper::class.java)
    }
}